package com.code.question3;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

public class CopyFile implements Runnable{
    private File sourceFile;
    private File targetFile;

    public File getSourceFile() {
        return sourceFile;
    }

    public void setSourceFile(File sourceFile) {
        this.sourceFile = sourceFile;
    }

    public File getTargetFile() {
        return targetFile;
    }

    public void setTargetFile(File targetFile) {
        this.targetFile = targetFile;
    }

    @Override
    public void run() {
        FileChannel inputFileSource= null;
        FileChannel outputFileSource = null;
        try {
            //获取源文件输入流通道
            inputFileSource = new FileInputStream(this.sourceFile).getChannel();
            //获取目标文件输出流通道
            if (!this.targetFile.exists()){
                this.targetFile.getParentFile().mkdirs();
            }
            outputFileSource = new FileOutputStream(this.targetFile).getChannel();
            System.out.println("正在复制文件，由"+this.sourceFile.getAbsolutePath()+"，复制到"+this.targetFile.getAbsolutePath());
            //文件流通道传输文件
            outputFileSource.transferFrom(inputFileSource, 0, inputFileSource.size());
            System.out.println("--------复制文件:"+this.sourceFile.getAbsolutePath()+"，复制到"+this.targetFile.getAbsolutePath()+"成功");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(null!=outputFileSource){
                try {
                    outputFileSource.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(null!=inputFileSource){
                try {
                    inputFileSource.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
